﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;

namespace XinYiOffice.Common
{
    /// <summary>
    /// 随机生成类
    /// </summary>
    public class RandomStringGenerator
    {
        private static readonly int defaultLength = 8;

        private static int GetSeed()
        {
            byte[] rndBytes = new byte[4];
            RNGCryptoServiceProvider rng =new RNGCryptoServiceProvider();

            rng.GetBytes(rndBytes);
            return BitConverter.ToInt32(rndBytes, 0);
        }
        
        private static string BuildRandomCodeAll(int length)
        {

            System.Random RandomObj = new System.Random(GetSeed());
            string buildRndCodeReturn = null;
            for (int i = 0; i < length; i++)
            {
                buildRndCodeReturn += (char)RandomObj.Next(33, 125);
            }

            return buildRndCodeReturn;
        }

        public static string GetRandomStringOfAll()
        {
            return BuildRandomCodeAll(defaultLength);
        }

        public static string GetRandomStringOfAll(int length)
        {
            return BuildRandomCodeAll(length);
        }



        private static string CharLower =

            "abcdefghijklmnopqrstuvwxyz";

        private static string CharUpper =

            "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

        private static string Number = "0123456789";
        
        private static string BuildRandomCodeOnly(

            string seedString, int length)
        {

            Random RandomObj = new Random(GetSeed());

            StringBuilder sb = new StringBuilder(length);

            for (int i = 0; i < length; i++)
            {

                sb.Append(seedString[RandomObj.Next(0,

                    seedString.Length - 1)]);

            }

            return sb.ToString();

        }

        public static string GetRandomString()
        {

            return BuildRandomCodeOnly(

                CharLower + Number, defaultLength);

        }



        public static string GetRandomString(int length)
        {

            return BuildRandomCodeOnly(CharLower + Number, length);

        }



        public static string GetRandomString(

            bool useUpper, bool useNumber)
        {

            string strTmp = CharLower;

            if (useUpper) strTmp += CharUpper;

            if (useNumber) strTmp += Number;



            return BuildRandomCodeOnly(strTmp, defaultLength);

        }



        public static string GetRandomString(

            int length, bool useUpper, bool useNumber)
        {

            string strTmp = CharLower;

            if (useUpper) strTmp += CharUpper;

            if (useNumber) strTmp += Number;



            return BuildRandomCodeOnly(strTmp, length);

        }

    }

}

